package keter.framework.web.server;

import org.eclipse.jetty.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.PathKit;
import com.jfinal.server.Scanner;

public class KeterServer {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(KeterServer.class);
    
    private static final String DEFAULT_WEBAPP_PATH = "src/main/webapp";
    private static final String DEFAULT_CONTEXT = "/";
    private static final int SCAN_INTERVAL_SECONDS = 2;

    /**
     * <p>Method ：start
     * <p>Description : 使用默认端口号(8080)和上下文(/)启动
     * 
     * @author  顾力行-gulixing@msn.com
     */
    public static void start(){
        start(8080,DEFAULT_CONTEXT);
    }
    
    public static void start(int port){
        start(port,DEFAULT_CONTEXT);
    }
    

    /**
     * 功能描述
     * @param port
     * @param context 
     * @author  gulixing@msn.com
     * @date    Jul 4, 2015
     */
    public static void start(int port, String context){
        start(port,context,DEFAULT_WEBAPP_PATH,SCAN_INTERVAL_SECONDS);
    }
    
    /**
     * <p>Method ：start
     * <p>Description : 方法功能描述
     *
     * @param port        端口号
     * @param context     上下文
     * @param webAppDir   web应用目录
     * @author  顾力行-gulixing@msn.com
     */
    public static void start(int port, String context, String webAppDir,int scanIntervalSeconds){
        Server server = JettyFactory.createServerInSource(port,context,webAppDir);
        try {
            server.start();
            System.out.println("[INFO] Server running at http://localhost:" + port + context);
//            System.out.println("[HINT] Hit [r] key to reload the application quickly");
            scan(scanIntervalSeconds,server);
            // 等待用户输入回车重载应用.
//            while (true) {
//                char c = (char) System.in.read();
//                if (c == 'r') {
//                    restartServer(server);
////                    JettyFactory.reloadContext(server);
//                }
//            }
        } catch (Exception e) {
            logger.error("server启动失败:",e);
        }
    }
    
   
    /**
     * <p>Method ：startWar
     * <p>Description : 从war包启动应用
     * @param port
     * @param context
     * @param warDir 
     * @author  gulixing@msn.com
     * @version 1.0.0
     * @date    Jul 4, 2015
     */
    public static void startWar(int port, String warDir){
        startWar(port,"/",warDir);
    }
    
    public static void startWar(int port, String context, String warPath){
        Server server = JettyFactory.createServerInWar(port,context,warPath);
        try {
            server.start();
            System.out.println("[INFO] deploying war: " + warPath);
            System.out.println("[INFO] Server running at http://localhost:" + port + context);
            server.join();
        } catch (Exception e) {
            logger.error("server启动失败:",e);
        }
    }

	private static void restartServer(Server server) throws Exception {
		server.stop();
		server.start();
		System.out.println("[INFO] Server restarted.");
        System.out.println("[HINT] Hit [r] key to reload the application quickly");
	}
    
    /**
     * Class时变更自动重启服务器：只在dubug模式下生效
     * @param scanIntervalSeconds
     * @param server 
     * @author  gulixing@msn.com
     * @date    Aug 14, 2015
     */
    private static void scan(int scanIntervalSeconds,Server server){
    	 // configureScanner
      if (scanIntervalSeconds > 0) {
//    	  logger.info("========={}============",PathKit.getRootClassPath());
          Scanner scanner = new Scanner(PathKit.getRootClassPath(), scanIntervalSeconds) {
              public void onChange() {
                  try {
                      System.err.println("\nLoading changes ......");
                      restartServer(server);
                      System.err.println("Loading complete.");
                  } catch (Exception e) {
                      System.err.println("Error reconfiguring/restarting webapp after change in watched files");
                      e.printStackTrace();
                  }
              }
          };
          System.out.println("Starting scanner at interval of " + scanIntervalSeconds + " seconds.");
          scanner.start();
      }
    }
    
}
